import UserService.User;
import UserService.UserDaoImp;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet(name="LoginServlet",value = "/LoginServlet")//路径的定向
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String username = req.getParameter("username");//获取表单传来的名字
        String password = req.getParameter("password");//密码
        String submitButton = req.getParameter("submitButton");//检测提交按钮
        String registerButton = req.getParameter("registerButton");//注册按钮
        String error="  ";

        if (submitButton != null) {
            // 用户按下了提交按钮
            // 执行提交按钮的逻辑

            UserDaoImp um = new UserDaoImp();
         //   ManageDaoImp m2=new ManageDaoImp();
            try {

             //   Manage m=m2.finduser(username);
                User u2 = um.finduser(username);//创建用户

                System.out.println(u2.getUname());//验证
                System.out.println(u2.getPassword());

                if (u2.getUname().equals(username) && u2.getPassword().equals(password)) {//用户名和密码一致.用户登录成功!
                    HttpSession session = req.getSession(true);
                    session.setMaxInactiveInterval(60 * 60);

                    User user=new User();//创建用户
                    user.setUname(username);//储存用户名和密码
                    user.setPassword(password);
                    System.out.println("1111");
                    session.setAttribute("user", user);//将用户名和密码传入session当中
                    // resp.sendRedirect("IndexServlet");
                    System.out.println("222");
                    req.getRequestDispatcher("userSite.jsp").forward(req, resp);


                } else {
//                resp.sendRedirect("UserLogin.jsp");
//                System.out.println("111");

                    error = " 用户名或密码错误 !  ";
                    req.setAttribute("error", error);

                    // req.getRequestDispatcher("UserLogin.jsp").forward(req,resp);
                    req.getRequestDispatcher("UserLogin.jsp").forward(req, resp);
                }

            } catch (Exception e) {
                e.printStackTrace();
                // 可以在这里设置一个默认的错误信息，例如：
                error = "查无此用户!";
                req.setAttribute("error", error);

                // req.getRequestDispatcher("UserLogin.jsp").forward(req,resp);
                req.getRequestDispatcher("UserLogin.jsp").forward(req, resp);
            }

        }
            else if (registerButton != null) {
            // 用户按下了注册按钮
            // 执行注册按钮的逻辑
            resp.sendRedirect("Register.jsp");
        }


    }


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }


}
